﻿using Orleans;
using Orleans.ApplicationParts;
using Orleans.Concurrency;
using Orleans.Providers;
using Orleans.Runtime;
using Sample.GrainService;
using Sample.Interfaces;
using System;
using System.Threading.Tasks;

namespace Sample.Implements
{
    /// <summary>
    /// 参数 ProviderName = OrleansStorage， 为配置节名称.配置其状态存储方式
    /// 状态类通过 Grain<UserServiceState> 装载
    /// 状态信息通过 this.State.* 操作
    /// </summary>
    //[StorageProvider(ProviderName = "OrleaneStorage")]

    // 对无状态工作人员谷物发出的请求始终在本地执行，
    // 即在发出请求的同一筒仓上执行，该筒仓是由在筒仓上运行的谷物发出的，还是由筒仓的客户端网关接收的。
    // 因此，从其他谷物或从客户端网关对无状态工人谷物的调用永远不会产生远程消息
    // [StatelessWorker]

    // 支持 再入(交错执行，理论效率稍微高，仍然执行在单线程)
    // [Reentrant]
    [StorageProvider(ProviderName = "UserServiceStorgeProvider")]
    public class UserService : Grain<UserServiceState>
        , IUserService   // 业务接口 (必须)
    {
        readonly IDataServiceClient DataServiceClient;
        readonly ITest _Test;

        /// <summary>
        /// 使用服务
        /// </summary>
        /// <param name="dataServiceClient"></param>
        public UserService(IDataServiceClient dataServiceClient, ITest test)
        {
            DataServiceClient = dataServiceClient;
            _Test = test;
        }

        public int Index { get; set; }

        public Task<bool> Exist(string mobileNumber)
        {
            RequestContext.Set("TraceId", new Guid());
            Console.WriteLine("GetPrimaryKeyLong: {0}", this.GetPrimaryKeyLong());
            return Task.FromResult(mobileNumber == "15252156614");
        }

        public Task AddMoney()
        {
            Index += 2;
            this.State.MyState = Index;
            int result = this.DataServiceClient.MyMethod().Result;
            result = this._Test.aaa();
            return Task.CompletedTask;
        }

        public Task<int> GetState() {
            return Task.FromResult(this.State.MyState);
        }

        public Task<int> GetMoney()
        {
            this.WriteStateAsync();
            
            return Task.FromResult(Index);
        }

        
    }
}
